package com.example.concurrentprogramming8016.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author liyanhao
 * @Date 2023-01-06 12:27
 * 使用信号量进行线程池控制
 */
public class SemaphorePool {
    private static final int MAX_AVAILABLE = 100;
    private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);

    public Object getItem() throws InterruptedException {
        available.acquire();
        return getNextAvailableItem();
    }

    public void putItem(Object x) {
        if (markAsUnused(x)) {
            available.release();
        }
    }

    // 管理何种项目
    protected Object[] items = new Object[MAX_AVAILABLE];//... whatever kinds of items being managed
    protected boolean[] used = new boolean[MAX_AVAILABLE];

    private Object getNextAvailableItem() {
        for (int i = 0; i < MAX_AVAILABLE; i++) {
            if (!used[i]) {
                used[i] = true;
                return items[i];
            }
        }
        return null;//not reached
    }


    private boolean markAsUnused(Object item) {
        for (int i = 0; i < MAX_AVAILABLE; ++i) {
            if (item == items[i]) {
                used[i] = false;
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

}
